"use strict";

const fs = require("fs");
const path = require("path");
const common = requireMod("common");
const commonLogger = log.getLogger("business.services");
const header = requireMod("header");
const Cache = requireMod("cache").local;
const jobsPath = getSysConfig("jobsPath");

function warpRespone(data) {
    return "(function(win){"+data+"})(window)";
}
exports.warpRespone = warpRespone;

/**
 * 设置不缓存返回头
 */
function setHeader(type) {
    type = type || "js";
    header.contentType(type, this);
    this.set("Pragma", "no-cache");
    this.set("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    this.set("P3P", 'CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA div COM NAV OTC NOI DSP COR"');
    this.set("Cache-Control", "max-age=0, no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
}
exports.setHeader = setHeader;

/**
 * 读取文件
 * @param  {Mix}    paths 文件列表，最后一个参数可以是自定义的 logger
 * @return {String}       文件数据
 */
function read(paths) {
    var args = Array.prototype.slice.call(arguments);
    var log;
    if (args && args.length) {
        log = args[args.length - 1];
        if (typeof(log) === "string") {
            log = commonLogger;
        } else {
            args.pop();
        }
    } else {
        log = commonLogger;
    }
    var dat;
    try {
        dat = fs.readFileSync(
            path.resolve.apply(path, args)
            ,"utf-8"
        );
    } catch(err) {
        log.warn(err);
    }
    return dat;
}
exports.read = read;

/**
 * 缓存对象
 * @type {Object}
 */
const CACHES = {
    "jobsCache": Cache(
        "JOBS_CACHE"
        ,{
            "maxAge": 1000 * 60 * 60 * 24 * 14
            ,"max": 200
        }
    )
};

/**
 * 获取或生成一个缓存实例
 * @param  {String} name 实例名称
 * @param  {Object} conf 缓存配置
 * @return {Object}      缓存实例对象
 */
function commonCache(name, conf) {
    if (CACHES[name]) {
        return CACHES[name];
    }
    if (conf) {
        CACHES[name] =  Cache(
            name
            ,conf
        );
    } else {
        commonLogger.error("Create Cache subject fail. Cache conf required.")
    }
}
commonCache.get = function (key, name) {
    name = name || "jobsCache";
    return CACHES[name].get(key);
}
commonCache.set = function (key, val, name) {
    name = name || "jobsCache";
    return CACHES[name].set(key, val);
}
commonCache.del = function (key, name) {
    name = name || "jobsCache";
    return CACHES[name].del(key);
}

exports.cache = commonCache;

/**
 * 生成一个建议 js loader
 * @param  {String} url 要加载的脚本的真实地址
 * @return {String}     脚本内容
 */
function buildScriptLoader(url) {
    var dat = read(jobsPath, "loader.js");
    dat = common.labelReplace(dat, {"url": url});
    return dat;
}
exports.buildScriptLoader = buildScriptLoader;

/**
 * 生成一个建议 js loader
 * @param  {String} url 要加载的脚本的真实地址
 * @return {String}     脚本内容
 */
function buildSDKScriptLoader(url) {
    var dat = read(jobsPath, "sdk-loader.js");
    dat = common.labelReplace(dat, {"url": url});
    return dat;
}
exports.buildSDKScriptLoader = buildSDKScriptLoader;
